import store from "../utils/store";
import * as antdHelper from "../utils/antd-helper";
import * as graphql from "./graphql";
import * as oss from "./oss";
import { Modal, Progress, notification } from "antd";
import { formatterSizeStr } from "../utils/formatter";
import webconfig from "../webconfig";
window.uploadingList = [];
window.isUploading = false;

export async function uploadFile(dirId, bucketName, file) {
  let ret;
  let accountType = store.get("accountType");
  let account = store.get("account");
  let space = account?.spaceInfo?.remainingSpace;
  // console.log({account,size:file.size});
  if (space && space < file.size) {
    return antdHelper.alertError(
      "The file size is larger than the remaining space."
    );
  }
  let uping = {
    id:new Date().valueOf(),
    per: 0,
    name: file.name,
    size: file.size,
    sizeStr: formatterSizeStr(file.size),
    state: "waiting",
  };
  window.uploadingList.push(uping);
  checkIsUploading();
  window.refreshUploadingFiles();
  const progressCb = (t) => {
    if (uping.state == "cancel") {
      return;
    }
    let p = t.percentComplete;
    if (p >= 100) {
      p = 99;
    }
    uping.per = p;
    uping.state = "pending";
    uping.speed = t.speed + t.speedUnit;
    uping.stop = function () {
      console.log("user cancel upload.");
      let xhr = t.xhr;
      xhr.abort();
      // xhr.upload.onprogress = null;
      // xhr.upload.onload = null;
      // xhr.upload.onerror = null;
      // xhr.upload.onabort = null;
      setTimeout(function () {
        uping.state = "cancel";
        uping.speed = "";
        window.refreshUploadingFiles();
        checkIsUploading();
      }, 500);
    };
    // console.log(window.uploadingList);
    window.refreshUploadingFiles();
    checkIsUploading();
  };
  try {
    if (accountType == "email") {
      // console.log({currDir});return;
      ret = await graphql.postFile(dirId, file, progressCb);
    } else {
      if (webconfig.uploadToGateway) {
        ret = await oss.uploadFile(file, bucketName, progressCb);
        if (ret.msg == "ok" && ret.data) {
          ret = await graphql.createFile(ret.data, file.name, dirId);
        }
      } else {
        let msg = `<Bytes>timestemp${new Date().valueOf()}</Bytes>`;
        let signedMsg = await oss.signMessage(account.address, msg);
        if (!signedMsg) {
          antdHelper.alertError("Sign fail");
          return false;
        }
        ret = await graphql.postFileForWalletAccount(
          dirId,
          file,
          progressCb,
          msg,
          signedMsg
        );
      }
    }
  } catch (error) {
    ret.msg = error.message;
  }
  if (!ret) {
    uping.state = "fail";
    return false;
  }
  if (ret.msg != "ok") {
    antdHelper.alertError(ret.msg);
    uping.state = "error";
    uping.error = ret.msg;
    return false;
  }
  antdHelper.notiOK("Upload success : " + file.name);
  uping.per = 100;
  uping.state = "success";
  // console.log(window.uploadingList);
  window.refreshUploadingFiles();
  checkIsUploading();
  if (window.refreshFileList) {
    window.refreshFileList();
  }
  if (window.refreshSpace) {
    window.refreshSpace();
  }
}
function checkIsUploading() {
  window.isUploading = window.uploadingList.find((t) => t.state == "pending")
    ? true
    : false;
  if (window.isUploading) {
    window.onbeforeunload = function (e) {
      e = e | window.event;
      if (e) {
        e.returnValue = "Close tips";
      }
      return false;
    };
  } else {
    window.onbeforeunload = null;
  }
}
